package com.jmu.edu.IMApplication.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.net.bean.FriendInvite;
import com.jmu.edu.IMApplication.utils.FriendUtils;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import java.io.IOException;

import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class AddFriendFragment extends Fragment {
    private static final String TAG = "addFriend";
    private ShapeableImageView avatarImage;
    private TextView nicknameText, signText;
    private EditText verifyMessageText, remarksText;
    private MaterialButton sendButton, backButton;
    private UserInfo userInfo;
    private String backTag = null;


    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    public AddFriendFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_add_friend, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        loadData();


    }

    private void loadData() {
        Bundle bundle = getArguments();
        // 默认单纯hide本界面
        if (bundle != null) {
            backTag = bundle.getString("backTag", null);
        } else {
            backTag = null;
        }
        ViewUtils.addBackListenerForHide(getView(), backButton);
        fillValuesInView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {

        } else {
            loadData();
        }
    }

    private void fillValuesInView() {
        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    Glide.with(avatarImage).load(bitmap).into(avatarImage);
                } else {
                    Glide.with(avatarImage).load(R.drawable.smc).into(avatarImage);
                }
            }
        });
        nicknameText.setText(WillowUtils.getNickName(userInfo));
        signText.setText(WillowUtils.getSignature(userInfo));
        remarksText.setText("");
        verifyMessageText.setText("");


    }

    private void initView() {
        avatarImage = getView().findViewById(R.id.fragment_add_friend_avatar);
        verifyMessageText = getView().findViewById(R.id.fragment_add_friend_verify_message);
        remarksText = getView().findViewById(R.id.fragment_add_friend_remarks);
        nicknameText = getView().findViewById(R.id.fragment_add_friend_nickname);
        signText = getView().findViewById(R.id.fragment_add_friend_sign);
        sendButton = getView().findViewById(R.id.fragment_add_friend_send);
        backButton = getView().findViewById(R.id.fragment_add_friend_back);
        initListener();
    }

    private void initListener() {
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = userInfo.getUserName();
                String verifyMessage = verifyMessageText.getText().toString();
                //将验证信息和username作为参数即可发送添加好友请求
                FriendUtils.addFriend(username, verifyMessage, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if (i == 0) {
                            backButton.callOnClick();
                            Toast.makeText(getContext(), "好友请求已发送", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), "发送好友请求失败" + "---" + i + "---" + s, Toast.LENGTH_SHORT).show();
                        }

                    }
                });
                //发送好友请求到数据库
                FriendInvite friendInvite = new FriendInvite();
                friendInvite.setStatus(FriendUtils.RECEIVE);
                friendInvite.setFromUsername(MyApplication.getUser().getUserName());
                friendInvite.setToUsername(username);
                friendInvite.setReason(verifyMessage);
                RequestBody requestBody = RequestBody.create(HttpUtil.JSON,new Gson().toJson(friendInvite));
                Request request = new Request.Builder().url(HttpUtil.URL_ADD_USER_INVITE).post(requestBody).build();
                MyApplication.getClient().newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, "onFailure: 发送好友请求", e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "onResponse: 发送好友请求"+response.body().string());
                    }
                });


            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (backTag == null) {
                    ViewUtils.hideFragment(AddFriendFragment.this);
                } else {
                    Fragment fragment = MyApplication.fragmentManager.findFragmentByTag(backTag);
                    ViewUtils.hideFragment(AddFriendFragment.this, fragment, backTag, R.anim.from_left, R.anim.out_right);
                }
            }
        });
    }
}